import React from 'react';
import MIcon from './MIcon';

class MBackTop extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			defaultBackTop: ["M-back-top"],
			scrollTop:0
		}
		this._handleScroll = this._handleScroll.bind(this);
		this._backTop = this._backTop.bind(this);
		this._toTop = this._toTop.bind(this);
	}
	_backTop(){
		this.props.onClick?this.props.onClick():"";
		this._toTop();
	}
	_toTop(){
		let self = this;
		let everyScroll = -self.state.scrollTop/10;
		window.scrollBy(0,everyScroll);
		if(document.body.scrollTop>0) { 
			setTimeout(function() {
				self._toTop();
			}, 10);
		}
	}
	_handleScroll(e){
		let self = this;
	    let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		let cacheStyle = self.state.defaultBackTop;
	    if(scrollTop > 0){
	    	if(cacheStyle.indexOf("M-in-top") < 0){
	    		cacheStyle.push("M-in-top");
	    	}	    			
	    }else{
	    	cacheStyle.pop();
	    }
	    self.setState({
			defaultBackTop: cacheStyle,
			scrollTop: scrollTop
		});
	}
	componentDidMount() {
		window.addEventListener('scroll', this._handleScroll);
	}
	componentWillUnmount() {
		window.removeEventListener('scroll', this._handleScroll);
	}
	render(){
		console.log("_backTop");  
		/*  rerender太多次了,看看有没有办法过滤下	*/
		return (
			<div className = {this.state.defaultBackTop.join(" ")} onClick = {this._backTop}>
				<MIcon type="arrowup" />
			</div>
		)
	}
}
module.exports = MBackTop;